<template>
	 <view>
	    <view class="goods-list">
	      <view v-for="(goods, i) in goodsList" :key="i" @click="gotoGoodsDetail(goods)">
	      <my-goods :goods="goods"></my-goods>
	      </view>
	    </view>
	  </view>
</template>

<script>
	export default {
		data() {
			return {
				// 请求参数对象
				queryObj: {
					// 查询关键词
					query: '',
					// 商品分类Id
					cid: '',
					// 页码值
					pagenum: 1,
					// 每页显示多少条数据
					pagesize: 10,
				},
				// 商品列表的数据
				  goodsList: [],
				  // 总数量，用来实现分页
				  total: 0,
				  //定义节流阀，避免频繁触发下拉刷新事件
				  flag:false
			};
		},
		onLoad(options){
			 this.queryObj.query = options.query || ''
			 this.queryObj.cid = options.cid || ''
			   this.getGoodsList()
		},
		methods:{
			async getGoodsList(cb) {
				//启用节流阀
				this.flag=true
			    // 发起请求
			    const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
				// 关闭节流阀
				this.flag=false
				//立即执行传入进来的参数
				cb&&cb()
			    if (res.meta.status !== 200) return uni.$showMsg()
			    // 为数据赋值
			    this.goodsList = [...this.goodsList,...res.message.goods]
			    this.total = res.message.total
			  },
			  gotoGoodsDetail(goods){
			  	uni.navigateTo({
			  		url:'../../subpkg/goods-detail/goods-detail?goods_id=' + goods.goods_id
			  	})
			  }
		},
		//上拉触底事件
		onReachBottom() {
			if(this.queryObj.pagenum * this.queryObj.pagesize >= this.total){
				uni.$showMsg('数据加载完毕！')
				return
			} 
			if(this.flag)return
			// 刷新后页码数加一
			this.queryObj.pagenum+1
			//重新发起请求获取数据
			this.getGoodsList()
		},
		//下拉刷新事件
		onPullDownRefresh(){
			this.queryObj.pagenum=1
			this.total=0
			this.goodsList=[],
			this.flag=false
			this.getGoodsList(()=>uni.stopPullDownRefresh())
		},
		
	}
</script>

<style lang="scss">

</style>
